package com.ccc.boot.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ccc.boot.exception.BusinessException;
import com.ccc.boot.response.ResponseCode;
import com.ccc.boot.system.entity.SysDict;
import com.ccc.boot.system.entity.SysDictInfo;
import com.ccc.boot.system.mapper.SysDictInfoMapper;
import com.ccc.boot.system.mapper.SysDictMapper;
import com.ccc.boot.system.service.SysDictInfoService;
import com.ccc.boot.system.service.SysDictService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 〈数据字典——服务层〉
 *
 * @author superC
 * @date 2022/3/29
 * @version 0.1.0
 */
@Service
public class SysDictServiceImpl implements SysDictService {

    protected static final Logger logger = LoggerFactory.getLogger(SysDictServiceImpl.class);

    @Autowired
    private SysDictMapper sysDictMapper;

    @Autowired
    private SysDictInfoService sysDictInfoService;

    @Autowired
    private SysDictInfoMapper sysDictInfoMapper;

    @Override
    public boolean add(SysDict sysDict) {
        QueryWrapper<SysDict> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(SysDict::getId,sysDict.getId());
        int count = sysDictMapper.selectCount(wrapper);
        if(count != 0){
            throw new BusinessException(ResponseCode.DATA_ALREADY_EXISTED);
        }
        return sysDictMapper.insert(sysDict)>0?true:false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(String id) {
        QueryWrapper<SysDict> wrapper1 = new QueryWrapper<>();
        wrapper1.lambda().eq(SysDict::getId,id);
        int count = sysDictMapper.selectCount(wrapper1);
        if(count == 0){
            throw new BusinessException(ResponseCode.RESULT_DATA_NONE);
        }
        SysDictInfo sysDictInfo = new SysDictInfo();
        sysDictInfo.setDictId(id);
        QueryWrapper<SysDictInfo> wrapper = new QueryWrapper<>(sysDictInfo);
        try {
            //删除主表数据字典
            sysDictMapper.deleteById(id);
            //删除从表数据字典
            sysDictInfoMapper.delete(wrapper);

            // 删除redis缓存数据
            sysDictInfoService.deleteDictCache(id);

        }catch (Exception e){
            logger.error("【捕获异常-删除操作】\r\n异常记录：", e);
            //手工回滚异常
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
        return true;
    }

    @Override
    public boolean update(SysDict sysDict) {
        QueryWrapper<SysDict> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(SysDict::getId,sysDict.getId());
        int count = sysDictMapper.selectCount(wrapper);
        if(count == 0){
            throw new BusinessException(ResponseCode.RESULT_DATA_NONE);
        }
        return sysDictMapper.updateById(sysDict)>0?true:false;
    }

    @Override
    public Set<String> getAllIds() {
        return sysDictMapper.getAllIds();
    }

    @Override
    public List<SysDict> getList() {
        LambdaQueryWrapper<SysDict> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(SysDict::getName);
        return sysDictMapper.selectList(wrapper);
    }

    @Override
    public Map<String, Map<String, Object>> getAllDictData() {
        Map<String, Map<String, Object>> resultMap = new HashMap<>();
        Set<String> ids = getAllIds();
        ids.forEach(id -> {
            // 获取id对应的数据字典
            Map<String, Object> codeMap = sysDictInfoService.selectMap(id);
            if (!codeMap.isEmpty()) {
                resultMap.put(id, codeMap);
            }
        });
        return resultMap;
    }

}
